//引入公共函数模块
let util = require('../../utils/util');

let printer = require('../../utils/printer');

let requestDomain = util.config('requestDomain');

let that;

//获取到APP实例
let app = getApp();

Page({
    
    //页面数据
    data: {

        connectFailed: false,

        contentList: [],

        storeFunInfo: [],

        selectedNotifyItem: {
            funId: '',
            height: 'auto',
            opacity: 1,
            timestamp: 0
        },

        serviceCheckStatus: true,

        lastDoneFunTimestamp: '',

        lastServingChangeTimestamp: '',

        lastOrderDoneTimestamp: '',

        cuePlayer: null,

        printerReady: false

    },

    onLoad: function() {

        if(!util.globalData('storeId')) {

            util.showError('系统错误', '未验证的商户');

            return;

        }

        that = this;

        if(util.status('logined')) {
            return;
        }

        wx.showToast({
            title: '加载数据中',
            icon: 'loading',
            mask: true,
            duration: 10000
        });

        //绑定消息触发的函数
        util.target('sysMsg', that.sysMsgHandler);
        util.target('userMsg', that.userMsgHandler);

        that.getStoreFunInfo(function(storeFunInfo) {
            that.data.storeFunInfo = storeFunInfo;
            that.recoverFunInfo(undefined, function() {
                that.recoverNoDoneOrder();
                wx.hideToast();
            });
            
        });
        console.log(app.globalData);

        util.status('appInit', true);

    },

    onShow: function() {
        wx.hideNavigationBarLoading();
        if(!util.status('connected')) {
            util.status('recryConnectDone', true);
            app.wsClose();
        }
        util.status('logined', true);
        //设置当前的连接状态
        that.setData({connectFailed: !util.status('connected')});
    },

    sysMsgHandler: function(event, msg) {

        switch(event) {
            case 'wsErrClose':
                that.setData({connectFailed: true});
            break;
            case 'wsRecryConnected':
                let {noDoneOrders, noReceiveFunLogs} = msg;
                wx.hideNavigationBarLoading();
                that.setData({connectFailed: false});
                that.recoverFunInfo(noReceiveFunLogs, function() {
                    that.recoverNoDoneOrder(noDoneOrders);
                });
            break;
            case 'storeFunDone': 
                that.otherStoreFunDone(msg);
            break;
            case 'orderPayDone':
                that.orderPayDone(msg);
            break;
            case 'orderServingChange':
                that.orderServingChange(msg);
            break;
            case 'orderDone':
                that.orderDoneTarget(msg);
            break;
        }

        console.log(event, msg);

    },

    userMsgHandler: function(event, msg) {

        console.log(event, msg);

        switch(event) {
            case 'storeFun': that.storeFunHandler(msg);
        }

    },

    printerInit: function() {
        let printerDeviceId = util.globalData('printerDeviceId');
        if (!printerDeviceId) {
            return;
        }
        printer.open({
            success: function () {
                printer.find({
                    success: function (deviceIdList) {
                        printer.connect({
                            deviceId: deviceIdList[0],
                            success: function() {

                            },
                            fail: function() {

                            }
                        });
                    },
                    fail: function () {

                    }
                });
            },
            fail: function () {

            }
        });
    },

    goPrinter: function() {
        wx.showModal({
            title: '提示',
            content: '打票机功能暂未开放噢，敬请期待！'
        });
        return;
        let {printerReady} = that.data;
        if (printerReady) {

        }
        else {
            wx.navigateTo({
                url: '/pages/printerManager/printerManager',
                fail: function() {
                    wx.showModal({
                        title: '跳转失败',
                        content: '跳转到打印机管理界面失败，请重试'
                    });
                }
            });
        }
    },

    recoverFunInfo: function(funList, callback) {
        let {noReceiveFunLogs} = util.globalData('loginData');
        let {contentList, storeFunInfo} = that.data;
        let tableNums = util.globalData('serviceTableNums');
        contentList = wx.getStorageSync('contentList') || [];
        if(funList) {
            noReceiveFunLogs = funList;
        }
        if(noReceiveFunLogs.length > 0) {
            noReceiveFunLogs.sort(function(a, b) {
                return b.timestamp - a.timestamp;
            });
            let temp = {};
            for(let funInfoIndex in storeFunInfo) {
                temp[storeFunInfo[funInfoIndex].funId] = storeFunInfo[funInfoIndex].funName;
            }
            for(let funIndex in noReceiveFunLogs) {
                let {funId, tableNum, timestamp} = noReceiveFunLogs[funIndex];
                if (tableNums != '*') {
                    let found = false;
                    for(let tableNumIndex in tableNums) {
                        if(tableNums[tableNumIndex] == tableNum) {
                            contentList.push({
                                type: 'funItem',
                                funId: funId,
                                tableNum: tableNum,
                                content: temp[funId],
                                timestamp: timestamp
                            });
                            break;
                        }
                        if(tableNumIndex == tableNums.length - 1 && !found) {
                            console.log('已拒收不属于自己的消息');
                            break;
                        }
                    }
                }
                else {
                    contentList.push({
                        type: 'funItem',
                        funId: funId,
                        tableNum: tableNum,
                        content: temp[funId],
                        timestamp: timestamp
                    });
                }
            }
        }
        that.data.contentList = contentList;
        callback();
    },

    recoverNoDoneOrder: function(orderList) {
        let {noDoneOrders} = util.globalData('loginData');
        let {contentList} = that.data;
        if(orderList) {
            noDoneOrders = orderList;
        }
        let temp = [];
        for(let contentIndex in contentList) {
            if(contentList[contentIndex].type == 'funItem') {
                temp.push(contentList[contentIndex]);
            }
        }

        if(noDoneOrders.length == 0) {
            contentList = [];
        }

        contentList = temp;
        console.log(contentList);
        console.log(noDoneOrders);

        that.setData({contentList: contentList});

        wx.setStorage({key: 'contentList', data: contentList});
        
        for(let orderIndex in noDoneOrders) {
            console.log(noDoneOrders[orderIndex]);
            that.orderPayDone(noDoneOrders[orderIndex]);
        }

    },

    getStoreFunInfo: function(callback) {

        wx.showNavigationBarLoading();

        wx.request({
          url: requestDomain + 'storeFun/find',
          data: {
              storeId: util.globalData('storeId'),
              _3rdSession: util.globalData('_3rdSession')
          },
          method: 'POST',
          success: function(result){

            wx.hideNavigationBarLoading();

            console.log(result);

            if(util.checkSuccess(result) && result.data && result.data.data) {

                callback(result.data.data);

            }
            else {

                util.showError('获取列表失败', '获取通知列表数据失败，请重新开启小程序再试');

            }

          },
          fail: function(err) {

            wx.hideNavigationBarLoading();

            console.log(err);

            util.showError('获取列表失败', '发起获取通知列表数据请求失败，请重新开启小程序再试');

          }
        })
    },

    storeFunHandler: function(funData) {
        let {funId, tableNum, timestamp} = funData;
        let {contentList, storeFunInfo} = that.data;
        let tableNums = util.globalData('serviceTableNums');
        let funName;
        if(tableNums != '*') {
            let found = false;
            for(let tableNumIndex in tableNums) {
                if(tableNums[tableNumIndex] == tableNum) {
                    break;
                }
                if(tableNumIndex == tableNums.length - 1 && !found) {
                    console.log('已拒收不属于自己的服务消息');
                    return;
                }
            }
        }
        util.playCue('sound1');
        for(let storeFunIndex in storeFunInfo) {
            if(storeFunInfo[storeFunIndex].funId == funId) {
                funName = storeFunInfo[storeFunIndex].funName;
            }
        }
        contentList.push({
            type: 'funItem',
            funId: funId,
            tableNum: tableNum,
            content: funName,
            timestamp: timestamp
        });
        contentList.sort(function(a, b) {
            return b.timestamp - a.timestamp;
        });
        that.setData({contentList: contentList});
        wx.setStorage({key: 'contentList', data: contentList});
    },

    serviceDone: function(e) {
        if(that.data.serviceCheckStatus) {
            that.data.serviceCheckStatus = false;
            let {funid, timestamp} = e.currentTarget.dataset;
            let {selectedNotifyItem, contentList} = that.data;
            selectedNotifyItem.funId = funid;
            selectedNotifyItem.height = 0;
            selectedNotifyItem.opacity = 0;
            selectedNotifyItem.timestamp = timestamp;
            that.setData({selectedNotifyItem: selectedNotifyItem});
            that.data.lastDoneFunTimestamp = Date.now();
            wx.request({
              url: requestDomain + 'storeFun/done',
              data: {
                  storeId: util.globalData('storeId'),
                  _3rdSession: util.globalData('_3rdSession'),
                  funId: funid,
                  timestamp: timestamp,
                  lastDoneFunTimestamp: that.data.lastDoneFunTimestamp
              },
              method: 'POST'
            });
            setTimeout(function() {
                for(let contentIndex in contentList) {
                    if(contentList[contentIndex].timestamp == timestamp) {
                        contentList.splice(contentIndex, 1);
                        that.setData({contentList: contentList});
                        wx.setStorage({key: 'contentList', data: contentList});
                    }
                }
                setTimeout(function() {
                    that.data.serviceCheckStatus = true;
                }, 300);
            }, 500);
        }
    },

    otherStoreFunDone: function(data) {
        console.log(data.funId, data.timestamp, data.lastDoneFunTimestamp);
        if(data.funId && data.timestamp && data.lastDoneFunTimestamp && data.lastDoneFunTimestamp != that.data.lastDoneFunTimestamp) {
            that.data.serviceCheckStatus = false;
            let {selectedNotifyItem, contentList} = that.data;
            selectedNotifyItem.funId = data.funId;
            selectedNotifyItem.height = 0;
            selectedNotifyItem.opacity = 0;
            selectedNotifyItem.timestamp = data.timestamp;
            that.setData({selectedNotifyItem: selectedNotifyItem});
            setTimeout(function() {
                for(let funIndex in contentList) {
                    console.log(contentList[funIndex].funId == data.funId && contentList[funIndex].timestamp == data.timestamp);
                    if(contentList[funIndex].funId == data.funId && contentList[funIndex].timestamp == data.timestamp) {
                        contentList.splice(funIndex, 1);
                        that.setData({contentList: contentList});
                        wx.setStorage({key: 'contentList', data: contentList});
                    }
                }
                setTimeout(function() {
                    that.data.serviceCheckStatus = true;
                }, 300);
            }, 500);
        }
    },

    changeServingStatus: function(e) {
        let {contentList} = that.data;
        let {orderid, foodid} = e.currentTarget.dataset;
        if(!foodid) {
            return;
        }
        for(let orderIndex in contentList) {
            if(contentList[orderIndex].type == 'orderItem' && contentList[orderIndex].orderId == orderid) {
                for(let foodIndex in contentList[orderIndex].goodsList) {
                    if(contentList[orderIndex].goodsList[foodIndex].foodId == foodid) {

                        that.data.lastServingChangeTimestamp = Date.now();

                        wx.showNavigationBarLoading();

                        wx.request({

                          url: requestDomain + 'order/setServing',

                          data: {

                            storeId: util.globalData('storeId'),

                            _3rdSession: util.globalData('_3rdSession'),

                            orderId: orderid,

                            foodId: foodid,

                            serving: !contentList[orderIndex].goodsList[foodIndex].serving,

                            timestamp: that.data.lastServingChangeTimestamp

                          },

                          method: 'POST',

                          success: function(result){

                              wx.hideNavigationBarLoading();
                            
                            if(util.checkSuccess(result) && result.data && result.data.data) {

                                contentList[orderIndex].goodsList[foodIndex].serving = !contentList[orderIndex].goodsList[foodIndex].serving;

                                that.setData({contentList: contentList});

                                wx.setStorage({key: 'contentList', data: contentList});

                            }
                            else {

                                util.showError('同步失败', '同步上菜状态时出现错误' + result.data.errMsg, result.data.errCode);

                            }

                          },

                          fail: function(err) {
                            
                            console.log(err);

                            wx.hideNavigationBarLoading();

                            util.showError('同步失败', '同步上菜状态请求发送失败');

                          }

                        });
                    }
                }
            }
        }
    },

    orderServingChange: function(servingData) {
        let {orderId, foodId, serving, timestamp} = servingData;
        let {contentList, lastServingChangeTimestamp} = that.data;
        if(timestamp != lastServingChangeTimestamp) {
            for(let orderIndex in contentList) {
                if(contentList[orderIndex].type == 'orderItem' && contentList[orderIndex].orderId == orderId) {
                    for(let foodIndex in contentList[orderIndex].goodsList) {
                        if(contentList[orderIndex].goodsList[foodIndex].foodId == foodId) {
                            contentList[orderIndex].goodsList[foodIndex].serving = serving;

                            that.setData({contentList: contentList});

                            wx.setStorage({key: 'contentList', data: contentList});
                        }
                    }
                }
            }
        }
    },

    orderMore: function(e) {
        let orderId = e.currentTarget.dataset.orderid;
        wx.navigateTo({
            url: '/pages/orderDetail/orderDetail?orderId=' + orderId,
            fail: function() {
                util.showError('跳转失败', '跳转到订单详情页面失败');
            }
        })
    },

    orderPayDone: function(orderData) {
        console.log(orderData);
        let {storeId, userId, orderId, tableNum, payMode, timestamp, goodsList} = orderData;
        let tableNums = util.globalData('serviceTableNums');
        timestamp *= 1000;
        if(tableNums != '*') {
            let found = false;
            for(let tableNumIndex in tableNums) {
                if(tableNums[tableNumIndex] == tableNum) {
                    break;
                }
                if(tableNumIndex == tableNums.length - 1 && !found) {
                    console.log('已拒收不属于自己的订单消息');
                    return;
                }
            }
        }
        util.playCue('sound1');
        if(storeId == util.globalData('storeId')) {
            let {contentList} = that.data;
            let orderStatus = that.getOrderStatus(payMode);
            let orderDate = that.getOrderDate(timestamp);
            let orderTotal = that.getOrderTotal(goodsList);
            console.log(orderTotal);
            contentList.unshift({
                type: 'orderItem',
                userId: userId,
                orderId: orderId,
                tableNum: tableNum,
                payMode: payMode,
                orderStatus: orderStatus,
                timestamp: timestamp,
                orderDate: orderDate,
                goodsList: goodsList,
                orderTotal: orderTotal,
            });
            contentList.sort(function(a, b) {
                return b.timestamp - a.timestamp;
            });
            that.setData({contentList: contentList});
            wx.setStorage({key: 'contentList', data: contentList});
        }
    },

    getOrderStatus: function(payMode) {
        switch(payMode) {
            case 'wxPay': return '已微信付款';
            case 'cashPay': return '等待现金付款';
        }
    },

    getOrderDate: function(timestamp) {
        let date = new Date(timestamp);
        let orderDate = util.formatTime(date);
        return orderDate;
    },

    getOrderTotal: function(goodsList) {
        let total = 0;
        for(let goodsIndex in goodsList) {
            let price = goodsList[goodsIndex].foodPrice || goodsList[goodsIndex].goodsPrice;
            let count = goodsList[goodsIndex].count || goodsList[goodsIndex].goodsCount;
            total += parseInt(price) * parseInt(count);
        }
        return total;
    },

    orderCheckPay: function(e) {
        let {orderid} = e.currentTarget.dataset;
        let {contentList} = that.data;
        for(let orderIndex in contentList) {
            if(contentList[orderIndex].type == 'orderItem' && contentList[orderIndex].orderId == orderid) {
                let userId = contentList[orderIndex].userId;
                let {tableNum, payMode, orderStatus, orderTotal, goodsList} = contentList[orderIndex];
                let tipList = {
                    wxPay: '您是否确定要结束' + tableNum + '号桌的订单？订单状态为 ' + orderStatus + '，订单总计为 ￥' + (orderTotal / 100),
                    cashPay: '您是否确认收到了' + tableNum + '号桌订单的 ￥' + (orderTotal / 100) + ' 现金？'
                };
                wx.showModal({
                    title: '结单提示',
                    content: tipList[payMode],
                    success: function(modal) {
                        if(modal.confirm) {
                            let noAllServing = true;
                            for(let goodsIndex in goodsList) {
                                console.log(goodsList[goodsIndex]);
                                if(!goodsList[goodsIndex].serving && goodsList[goodsIndex].foodId) {
                                    noAllServing = false;
                                    wx.showModal({
                                        title: '结单提示',
                                        content: '此订单还未完成，是否强制结单？',
                                        success: function(modal2) {
                                            if(modal2.confirm) {
                                                that.orderDone(userId, orderid);
                                            }
                                        }
                                    });
                                    break;
                                }
                            }
                            if(noAllServing) {
                                that.orderDone(userId, orderid);
                            }
                        }
                    }
                });

            }
        }
    },

    removeOrderItem: function(orderId) {
        let {contentList} = that.data;
        for(let orderIndex in contentList) {
            console.log(contentList[orderIndex]);
            if(contentList[orderIndex].type == 'orderItem' && contentList[orderIndex].orderId == orderId) {
                contentList.splice(orderIndex, 1);
                break;
            }
        }
        that.setData({contentList: contentList});
        wx.setStorageSync('contentList', contentList);
    },

    orderDoneTarget: function(doneData) {
        if(doneData.timestamp != that.data.lastOrderDoneTimestamp) {
            that.removeOrderItem(doneData.orderId);
        }
    },

    orderDone: function(userId, orderId) {
        wx.showNavigationBarLoading();

        that.data.lastOrderDoneTimestamp = Date.now();

        wx.request({
          url: requestDomain + 'order/done',

          data: {

            storeId: util.globalData('storeId'),

            _3rdSession: util.globalData('_3rdSession'),

            userId: userId,

            orderId: orderId,

            timestamp: that.data.lastOrderDoneTimestamp

          },

          method: 'POST',

          success: function(result){

            wx.hideNavigationBarLoading();

            let errList = {
		        '-0104': '创建此订单的用户还未进行支付操作',
		        '-0105': '此订单已经在其它服务端完成结单',
		        '-0106': '您所对应的商户已收取此订单的相关款项',
		        '-0107': '更新此通过微信支付的订单的状态失败，请重试',
		        '-0108': '更新此通过现金支付的订单的状态失败，请重试',
		        '-0109': '系统无法识别此订单的支付方式，请重试',
                '-0110': '订单用户不匹配，请重试',
		        '-0111': '查询此订单的数据失败，请重试',
		        '-0112': '系统找不到此订单，订单可能出现错误或永久清除，请重试'
            };
              
            if(util.checkSuccess(result) && result.data && result.data.data) {

                wx.showToast({
                    title: '结单成功',
                    icon: 'success'
                });

                console.log(result);

                that.removeOrderItem(orderId);

            }
            else if(util.checkSuccess(result, errList)) {

                let errCode = result.data.errCode;

                if(errCode == '-0105' || errCode == '-0106') {
                    
                    that.removeOrderItem(orderId);

                }

                wx.showModal({
                    title: '结单失败',
                    content: errList[result.data.errCode]
                });

            }
            else {

                util.showError('结单失败', '在处理结单请求时发生错误 ' + result.data.errMsg, result.data.errCode);

            }
            
          },

          fail: function(err) {
            
            console.log(err);

            wx.hideNavigationBarLoading();

            util.showError('结单失败', '发起结束订单请求失败，请重试');

          }

        });
    }

});